/**
 * 通用uni-app网络请求
 * 基于 Promise 对象实现更简单的 request 使用方式，支持请求和响应拦截
 */
import tool from './tool.js'
import {
	baseUrl
} from "@/utils/global.js"

export default {
	config: {
		// 请求的公共url
		baseUrl: baseUrl, // 并非真实接口地址，换成自己的接口地址
		header: {
			'Authorization': 'Basic c2FiZXI6c2FiZXJfc2VjcmV0',
		},
		data: {},
		method: "GET",
		dataType: "json",
		/* 如设为json，会对返回的数据做一次 JSON.parse */
		responseType: "text",
		success() {},
		fail() {},
		complete() {}
	},
	// 请求拦截器
	interceptor: {
		request: null,
		response: null
	},
	request(options) {
		if (!options) {
			options = {}
		}

		options.baseUrl = options.baseUrl || this.config.baseUrl
		options.dataType = options.dataType || this.config.dataType
		options.url = options.baseUrl + options.url
		options.data = options.data || {}
		options.method = options.method || this.config.method
		options.header = options.header || {
			'Authorization': 'Basic bWluaTptaW5pX3NlY3JldA==',
			"Blade-Auth": "bearer " + (uni.getStorageSync('accessToken') || ''),
			'User-Type':'app',
			'Longitude':uni.getStorageSync('Longitude') || '',
			'Latitude':uni.getStorageSync('Latitude') || ''
		}
		// 基于 Promise 的网络请求
		return new Promise((resolve, reject) => {
			uni.showLoading({
				title: '加载中...'
			})
			let _config = null
			options.complete = (response) => {
				try {
					uni.hideLoading()
				} catch (e) {
					console.warn('hideLoading error:', e)
				}
				let statusCode = response.statusCode
				response.config = _config
				if (process.env.NODE_ENV === 'development') {
					if (statusCode === 200) {
						// console.log("【" + _config.requestId + "】 结果：" + JSON.stringify(response.data))
					}
				}
				if (this.interceptor.response) {
					let newResponse = this.interceptor.response(response)
					if (newResponse) {
						response = newResponse
					}
				}
				// 结构出code、msg
				let { code, msg } = response.data
				
				if (code === 401) {
					// 清除无效的登录信息
					uni.removeStorageSync('accessToken')
					uni.removeStorageSync('authInfo')
					uni.removeStorageSync('userInfo')
					
					uni.reLaunch({
						url:'/pages/login/login'
					})
					tool.msg('登录已过期，请重新登录！')
					reject(response)
				} else if (code === 200) {
					resolve(response.data)
				} else {
					// tool.msg(msg)
					resolve(response.data)
				}
				
			}
			_config = Object.assign({}, this.config, options)
			_config.requestId = new Date().getTime()

			if (this.interceptor.request) {
				this.interceptor.request(_config)
			}
			uni.request(_config);
		});
	},
	// get请求
	get(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'GET'
		return this.request(options)
	},
	// post请求
	post(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	},
	// put请求
	put(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'PUT'
		return this.request(options)
	},
	// delete请求
	delete(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'DELETE'
		return this.request(options)
	},
	uploadFile(path) {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: baseUrl+'/blade-resource/oss/endpoint/put-file',
				filePath: path,
				name: 'file',
				header: { //（根据自身接口要求选择）
					'Authorization': 'Basic bWluaTptaW5pX3NlY3JldA==',
					"Blade-Auth":"bearer "+ uni.getStorageSync('accessToken')
				},
				success: res => {
					const imgRes = JSON.parse(res.data)
					if (imgRes.code == 200) {
						resolve(imgRes.data)
					} else {
						reject('上传失败');
					}
				},
				fail: () => {
					reject('网络错误');
				}
			});
		})
	}
}